<template>
  <div class="warehouseAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button" v-if="!contactAddShow">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(warehouseFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon>返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item name="1" v-if="!contactAddShow" class="transform-down">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType === "detail" ? "" : pageType === "add" ? "新增" : "编辑"
            }}仓库信息</span
          >
        </template>
        <div class="warehouse-info">
          <el-form
            :model="warehouseForm"
            ref="warehouseFormRef"
            :rules="queryRules"
            label-width="100px"
            v-enterToNext
            label-position="right"
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="仓库编号：">
                  <el-input
                    ref="refInput"
                    v-model="warehouseForm.warehouseCode"
                    placeholder="自动生成"
                    clearable
                    disabled
                    class="search-input"
                    label-width="110"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="仓库名称："
                  label-width="150"
                  prop="warehouseName"
                >
                  <el-input
                    ref="refInput"
                    v-model="warehouseForm.warehouseName"
                    placeholder="请输入"
                    clearable
                    maxlength="20"
                    class="search-input"
                    label-width="110"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="所属公司："
                  prop="companyId"
                  label-width="120"
                >
                  <el-select
                    v-model="warehouseForm.companyId"
                    placeholder="请选择所属公司"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in deptOptions"
                      :key="dict.companyId"
                      :label="dict.companyName"
                      :value="dict.companyId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0" style="padding-bottom: 10px">
              <el-col :span="12">
                <el-form-item
                  label="仓库地址："
                  label-width="100"
                  prop="warehouseAddress"
                >
                  <el-input
                    style="width: 100%"
                    v-model="warehouseForm.warehouseAddress"
                    placeholder="请输入"
                    clearable
                    maxlength="50"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注：" label-width="120">
                  <el-input
                    maxlength="2000"
                    style="width: 100%"
                    :rows="2"
                    v-model="warehouseForm.remarks"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                  <!-- type="textarea" -->
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 添加联系人 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        v-if="contactAddShow"
        class="transform-up"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">添加联系人</span>
        </template>
        <div class="warehouse-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="120px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="联系人姓名：" prop="name">
                  <!-- <el-select
                    ref="selectInput"
                    v-model="contactForm.userId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    filterable
                    @change="handleUserChange"
                  >
                    <el-option
                      v-for="dict in userOptions"
                      :key="dict.userId"
                      :label="dict.name"
                      :value="dict.userId"
                    />
                  </el-select> -->
                  <el-select
                    ref="selectInput"
                    v-model="contactForm.userId"
                    style="width: 268px"
                    placeholder="请选择"
                    clearable
                    filterable
                    popper-class="custom-dropdown"
                    @change="handleUserChange"
                  >
                    <div class="dropdown-slot">
                      <span
                        style="
                          float: left;
                          color: #8492a6;
                          margin: 0 0px 0 20px;
                        "
                        >人员姓名</span
                      >
                      <span style="margin: 0 80px 0 56px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 10px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </div>
                    <div class="scrollable-options">
                      <el-option
                        v-for="item in userOptions"
                        :key="item.userId"
                        :label="item.name"
                        :value="item.userId"
                      >
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            float: left;
                            color: #8492a6;
                          "
                          >{{ item.name }}</span
                        >
                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 15px 0 23px;
                            color: #8492a6;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                          "
                          >{{ item.phone ? item.phone : "--" }}</span
                        >

                        <span
                          style="
                            display: inline-block;
                            width: 125px;
                            margin: 0 0px 0 0px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.postName }}
                        </span>
                        <span
                          style="
                            display: inline-block;
                            width: 80px;
                            font-size: 13px;
                            transform: translateY(-11px);
                          "
                        >
                          {{ item.deptName }}
                        </span>
                      </el-option>
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系方式：">
                  <el-input
                    v-model="contactForm.phone"
                    disabled
                    placeholder="自动回显"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职位：" label-width="150">
                  <el-input
                    disabled
                    v-model="contactForm.postName"
                    placeholder="自动回显"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门：" label-width="120">
                  <el-input
                    disabled
                    v-model="contactForm.deptName"
                    placeholder="自动回显"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 负责人信息 -->
      <el-collapse-item
        name="3"
        style="position: relative"
        class="transform-down"
        disabled
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">负责人信息</span>
          <div
            v-if="pageType !== 'detail' && !contactAddShow"
            class="nofixed-search-button button-position"
          >
            <el-button class="btn add" @click.stop="handleContactOperate"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
          <div
            class="nofixed-search-button button-position"
            v-else
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click.stop="handleWarehouseBack"
              ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="warehouseForm.warehouseContactInfoVos"
            border
            :height="
              pageType === 'detail'
                ? '100%'
                : contactAddShow
                ? '420px'
                : '400px'
            "
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <el-icon
                    title="编辑"
                    color="#FFB700"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('edit', row, $index)"
                  >
                    <Edit />
                  </el-icon>
                  <el-icon
                    title="删除"
                    color="#E33838"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('delete', row, $index)"
                  >
                    <Delete />
                  </el-icon>
                </div> </template
            ></el-table-column>
            <el-table-column
              label="联系人姓名"
              prop="name"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="联系方式"
              prop="phone"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="职位"
              prop="postName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="部门"
              prop="deptName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <el-dialog
    :title="operateType !== 'edit' ? '添加负责人' : '编辑负责人'"
    v-model="operateDialogShow"
    style="margin-top: 20vh !important"
    width="1400px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :close="handleWarehouseBack"
  >
    <!-- class="supplier-info" -->
    <div>
      <el-form
        style="height: 230px"
        :model="contactForm"
        ref="contactFormRef"
        :rules="queryContactRules"
        label-width="120px"
        v-enterToNext
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="联系人姓名：" prop="name">
              <!-- <el-select
                    ref="selectInput"
                    v-model="contactForm.userId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    filterable
                    @change="handleUserChange"
                  >
                    <el-option
                      v-for="dict in userOptions"
                      :key="dict.userId"
                      :label="dict.name"
                      :value="dict.userId"
                    />
                  </el-select> -->
              <el-select
              v-if="userOptions && userOptions.length"
                ref="selectInput"
                v-model="contactForm.userId"
                style="width: 268px"
                placeholder="请选择"
                clearable
                filterable
                popper-class="custom-dropdown"
                @change="handleUserChange"
              >
                <div class="dropdown-slot">
                  <span
                    style="float: left; color: #8492a6; margin: 0 0px 0 20px"
                    >人员姓名</span
                  >
                  <span style="margin: 0 80px 0 56px; color: #8492a6"
                    >联系方式</span
                  >
                  <span
                    style="
                      margin: 0 100px 0 10px;
                      color: #8492a6;
                      font-size: 13px;
                    "
                    >职位</span
                  >
                  <span style="color: #8492a6; font-size: 13px">部门</span>
                </div>
                <div class="scrollable-options">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.name"
                    :value="item.userId"
                  >
                    <span
                      style="
                        display: inline-block;
                        width: 80px;
                        float: left;
                        color: #8492a6;
                      "
                      >{{ item.name }}</span
                    >
                    <span
                      style="
                        display: inline-block;
                        width: 125px;
                        margin: 0 15px 0 23px;
                        color: #8492a6;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                      "
                      >{{ item.phone ? item.phone : "--" }}</span
                    >

                    <span
                      style="
                        display: inline-block;
                        width: 125px;
                        margin: 0 0px 0 0px;
                        font-size: 13px;
                        transform: translateY(-11px);
                      "
                    >
                      {{ item.postName }}
                    </span>
                    <span
                      style="
                        display: inline-block;
                        width: 80px;
                        font-size: 13px;
                        transform: translateY(-11px);
                      "
                    >
                      {{ item.deptName }}
                    </span>
                  </el-option>
                </div>
              </el-select>
              <el-select
              v-else
                    ref="selectInput"
                    v-model="contactForm.userId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    filterable
                    @change="handleUserChange"
                  >
                    <el-option
                      v-for="dict in []"
                      :key="dict.userId"
                      :label="dict.name"
                      :value="dict.userId"
                    />
                  </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式：">
              <el-input
                v-model="contactForm.phone"
                disabled
                placeholder="自动回显"
                clearable
                class="search-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位：" label-width="150">
              <el-input
                disabled
                v-model="contactForm.postName"
                placeholder="自动回显"
                clearable
                class="search-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门：" label-width="120">
              <el-input
                disabled
                v-model="contactForm.deptName"
                placeholder="自动回显"
                clearable
                class="search-input"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <!--  class="customer-info" -->

      <div class="dialog-footer">
        <el-button
          style="color: #fff; background-color: rgba(67, 207, 124, 1)"
          @click="handleContactAdd(contactFormRef)"
          >保存</el-button
        >

        <el-button style="background-color: #fff" @click="handleWarehouseBack()"
          >取 消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { selectCompanyByList } from "@/api/system/dept";
import {
  addWarehouseApi,
  getUserList,
  getWarehouseApi,
  editWarehouseApi,
} from "@/api/information/warehouse.js";
import { deptTreeSelect } from "@/api/system/user";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 仓库新增组件显隐
  "warehouseAddShow",
  // 更新仓库新增组件显隐
  "update:warehouseAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 仓库表单引用
const warehouseFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 详情加载效果
const detailInfoShow = ref(false);
// 新增编辑弹窗显隐
const operateDialogShow = ref(false);
// 部门列表
const deptOptions = ref(undefined);
// 用户列表
const userOptions = ref(undefined);
// 输入框引用
const refInput = ref();
// 下拉框引用
const selectInput = ref();
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 仓库表单数据模板
const warehouseFormTemplate = {
  warehouseCode: null,
  companyId: null, // 部门id
  position: "", // 仓位
  remarks: "", // 备注
  warehouseAddress: "", // 仓库地址
  warehouseContactInfoVos: [], // 	负责人
  warehouseName: "", //	仓库名称
};
// 联系人表单数据模板
const contactFormTemplate = {
  contactId: null, // 联系人id
  deptName: "", //	部门名称
  name: "", //联系人姓名
  phone: "", //	联系方式
  postName: "", //岗位名称
  remarks: "", // 	备注信息
  userId: null, //用户ID
  warehouseId: null, //	物料id
};
const data = reactive({
  // 仓库表单
  warehouseForm: JSON.parse(JSON.stringify(warehouseFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 仓库表单校验规则
  queryRules: {
    warehouseName: [
      { required: true, message: "请输入仓库名称", trigger: "blur" },
    ],
    companyId: [
      { required: true, message: "请选择所属公司", trigger: "change" },
    ],
    warehouseAddress: [
      { required: true, message: "请输入仓库地址", trigger: "blur" },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    name: [{ required: true, message: "请选择联系人姓名", trigger: "blur" }],
  },
});
const { warehouseForm, contactForm, queryRules, queryContactRules } =
  toRefs(data);

/**
 * @description: 保存
 * @param {Object} warehouseFormRef 仓库表单引用
 */
const handleAddSave = async (warehouseFormRef) => {
  if (!warehouseFormRef) return;
  await warehouseFormRef.validate(async (valid, fields) => {
    if (valid) {
      if (warehouseForm.value.warehouseContactInfoVos.length == 0) {
        return ElMessage.warning("请添加负责人！");
      }
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          let res;
          if (!warehouseForm.value.warehouseId) {
            res = await addWarehouseApi(warehouseForm.value);
          } else {
            res = await editWarehouseApi(warehouseForm.value);
          }
          if (res.code === 200) {
            emit("update:warehouseAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            warehouseForm.value = JSON.parse(
              JSON.stringify(warehouseFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:warehouseAddShow", false);
    warehouseForm.value = JSON.parse(JSON.stringify(warehouseFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:warehouseAddShow", false);
        warehouseForm.value = JSON.parse(JSON.stringify(warehouseFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;

  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存负责人数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (operateType.value === "edit") {
            warehouseForm.value.warehouseContactInfoVos[tableIndex.value] =
              JSON.parse(JSON.stringify(contactForm.value));
          } else {
            warehouseForm.value.warehouseContactInfoVos.push(
              JSON.parse(JSON.stringify({ ...contactForm.value }))
            );
          }
          contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
          contactFormRef.resetFields();
          operateDialogShow.value = false;
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  operateDialogShow.value = true;
  // contactAddShow.value = true;
  operateType.value = "add";
  setTimeout(() => {
    selectInput.value.focus(); // 聚焦
  }, 800);
};

/**
 * @description: 联系人返回
 */
const handleWarehouseBack = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
  operateDialogShow.value = false;
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    operateDialogShow.value = true;
    operateType.value = "edit";
    // setTimeout(() => {
    //   selectInput.value.focus(); // 聚焦
    // }, 800);;
  } else {
    ElMessageBox.confirm("此操作将删除该负责人，是否继续？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
      type: "warning",
    })
      .then(async () => {
        warehouseForm.value.warehouseContactInfoVos.splice(tabIndex, 1);
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 当前值
 */
const handleUserChange = (value) => {
  userOptions.value.forEach((item) => {
    if (item.userId === value) {
      contactForm.value.userId = item.userId;
      contactForm.value.name = item.name;
      contactForm.value.phone = item.phone;
      contactForm.value.postName = item.postName;
      contactForm.value.deptName = item.deptName;
    }
  });
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  try {
    detailInfoShow.value = true;
    const res = await getWarehouseApi(id);
    warehouseForm.value = res;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 部门列表
  await selectCompanyByList().then((res) => {
    if (res.length > 0) {
      deptOptions.value = res;
    }
  });
  // 人员列表
  await getUserList().then((res) => {
    userOptions.value = res;
  });
}

onMounted(() => {
  getDicts();
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}
.warehouseAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }

  .warehouse-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }
}
</style>

<style>
.custom-dropdown .dropdown-slot {
  height: 28px;
  line-height: 28px;
}

.custom-dropdown .scrollable-options {
  max-height: 200px; /* 根据需要设置合适的高度 */
  overflow-y: auto;
}

/* .dialogWareBox .el-dialog__body {
  height: 740px !important;
} */
</style>
